using System;
using System.Collections.Generic;
using System.Text;
using Org.BouncyCastle.Bcpg.OpenPgp;
using Org.BouncyCastle.Bcpg;
using System.IO;
namespace Pbdms.Common.CryptoUtils
{
    public class SecretKeyManager
    {
        private PgpSecretKeyRing secRing;
        string location = Pbdms.Common.Global.startupPath() + "//Data//secretkeyring.asc";
        public SecretKeyManager()
        {
            Stream inputStreamtemp = null;
            Stream inputStream = null;
            try
            {

                inputStreamtemp = File.OpenRead(location);
                //retrieve the orignal public key ring file
                inputStream = PgpUtilities.GetDecoderStream(inputStreamtemp);
                secRing = new PgpSecretKeyRing(inputStream);
                
            }
            catch (Exception ex)
            {
                secRing = null;

            }
            finally
            {
                inputStream.Close();
                inputStreamtemp.Close();
            }
        }
        public PgpSecretKey getSecretKey()
        {
            return secRing.GetSecretKey();
        }
        public void replaceSecretKey(PgpSecretKey key)
        {
            secRing=new PgpSecretKeyRing(key.GetEncoded());
        }
        public Boolean isEmpty()
        {
            return (secRing == null);
        }
        public void close()
        {
            Stream inputStream = null, inputStreamtemp = null;
            try
            {

                inputStreamtemp = File.Create(location);
                inputStream = new ArmoredOutputStream(inputStreamtemp);
                secRing.Encode(inputStream);
                inputStream.Close();
                inputStreamtemp.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("cannot close the datbase");
            }
            finally
            {
                inputStream.Close();
                inputStreamtemp.Close();
            }
        }
    }
}
